//
//  ExploreViewController.m
//  EDPS
//
//  Created by 张维扬 on 15/11/23.
//  Copyright © 2015年 张维扬. All rights reserved.
//

#import "ExploreViewController.h"
#import "ZWY_NetHandle.h"
#import "ExploreModel.h"
#import "ExploreCollectionViewCell.h"
#import "ExploreTableViewCell.h"
#import "ExploreStoryTableViewCell.h"
#import "Masonry.h"
#import "CirculateCollectionViewCell.h"
#import "imgNameModel.h"
#import "AllStoryViewController.h"
#import "DetailStoryViewController.h"
#import "IdModel.h"
#import "DetailTravelViewController.h"
#import "CirculateViewController.h"
#import "MBProgressHUD.h"
#import "MapViewController.h"
#import "AVPlayerViewController.h"
@interface ExploreViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UICollectionView *circulateView; //轮播图
@property (nonatomic, strong) NSMutableArray * circulate_dataArr;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSTimer *timer;//定时器
@property (nonatomic, strong) NSMutableArray *story_dataArr;//cell数据
@property (nonatomic, strong) NSMutableArray *travel_dataArr;
@property (nonatomic, strong) NSMutableArray *story_idArr;
@property (nonatomic, strong) NSMutableArray *travel_idArr;
@property (nonatomic, strong) NSMutableArray * travel_UserArr;
@property (nonatomic, strong) NSMutableArray * story_UserArr;
@property (nonatomic, strong) UIView *sectionOne_View;//第一个分区头视图
@property (nonatomic, strong) UIView *sectionTwo_View;// 第二个分区头视图
@property (nonatomic, strong) MBProgressHUD *HUD;
@end
@implementation ExploreViewController
{
    CGFloat contentOffsetY;//当前偏移量y值
    CGFloat oldContentOffsetY;
    CGFloat newContentOffsetY;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.title = @"探索";
    // 隐藏navagation
    self.navigationController.navigationBarHidden = NO;
    self.navigationController.toolbarHidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = RGBA(253, 244, 233, 1);
    // 小菊花
    [self createMBProgress];
    
    // 请求数据
    [self getData];
    
    // 右面按钮
    self.navigationController.navigationBar.translucent = NO;
    UIButton *nearBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    nearBtn.frame = CGRectMake(1, 1, ScreenWidth / 75 * 5, ScreenWidth / 75 * 5);
    nearBtn.tintColor = [UIColor blackColor];
    [nearBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-fujin"] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:nearBtn];
    [nearBtn addTarget:self action:@selector(nearBtn_action) forControlEvents:UIControlEventTouchUpInside];
    // 左面按钮
    UIButton *playerBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    playerBtn.frame = CGRectMake(1, 1, ScreenWidth / 75 * 5, ScreenWidth / 75 * 5);
    playerBtn.tintColor = [UIColor blackColor];
    [playerBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-fujin"] forState:UIControlStateNormal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:playerBtn];
    [playerBtn addTarget:self action:@selector(playerBtn_action) forControlEvents:UIControlEventTouchUpInside];
    
}
- (void)playerBtn_action
{
    AVPlayerViewController *av = [[AVPlayerViewController alloc] init];
    av.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:av animated:YES];
}
- (void)nearBtn_action
{
    MapViewController *map = [[MapViewController alloc] init];
    map.hidesBottomBarWhenPushed = YES;
    [map.navigationController setNavigationBarHidden:YES animated:YES];
    [self.navigationController pushViewController:map animated:YES];
}
#pragma mark - 小菊花
- (void)createMBProgress
{
    self.HUD = [[MBProgressHUD alloc]initWithView:self.view];
    self.HUD.alpha = 0.5;
    [self.view addSubview:self.HUD];
    self.HUD.labelText = @"加载中...";
    [self.HUD show:YES];
}
#pragma mark - 请求数据
- (void)getData
{
    NSString *url = @"http://api.breadtrip.com/v2/index/?lat=38.8802706535603&lng=121.54089204778&sign=dfcaa3638dd2a27e24a726ba2d2fd3cd";
    [ZWY_NetHandle getURL:url Cookie:nil parameter:nil result:^(id result) {
        
        // 轮播图数据
        self.circulate_dataArr = [ExploreModel transformWithArray:result[@"data"][@"elements"][0][@"data"][0]];
        // 把轮播图第一张图片加到最后面
        [self.circulate_dataArr addObject:[self.circulate_dataArr firstObject]];
        // 每日精彩故事数据
        self.story_dataArr = [NSMutableArray array];
        self.story_UserArr = [NSMutableArray array];
        self.story_idArr = [NSMutableArray array];
        for (NSDictionary *dic in result[@"data"][@"elements"]) {
            if ([dic[@"type"] integerValue] == 10) {
                [self.story_dataArr addObject:dic[@"data"][0]];
                [self.story_UserArr addObject:dic[@"data"][0][@"user"]];
                [self.story_idArr addObject:dic[@"data"][0]];
            }
        }
        self.story_dataArr = [ExploreModel transformWithArray:self.story_dataArr];
        // 每日精彩故事用户数据
        self.story_UserArr = [imgNameModel transformWithArray:self.story_UserArr];
        // 每日精彩故事点击传id
        self.story_idArr = [IdModel transformWithArray:self.story_idArr];
        // 精彩游记和专题数据
        self.travel_dataArr = [NSMutableArray array];
        self.travel_UserArr = [NSMutableArray array];
        self.travel_idArr = [NSMutableArray array];
        for (NSDictionary *dic in result[@"data"][@"elements"]) {
            if ([dic[@"type"] integerValue] == 4) {
                [self.travel_dataArr addObject:dic[@"data"][0]];
                [self.travel_UserArr addObject:dic[@"data"][0][@"user"]];
                [self.travel_idArr addObject:dic[@"data"][0]];
            }
        }
        self.travel_dataArr = [ExploreModel transformWithArray:self.travel_dataArr];
        // 精彩游记和专题上面用户数据
        self.travel_UserArr = [imgNameModel transformWithArray:self.travel_UserArr];
        // 游记点击传id
        self.travel_idArr = [IdModel transformWithArray:self.travel_idArr];
        
        //        NSLog(@"%@", self.circulate_dataArr);
        [self.tableView reloadData];
        [self.circulateView reloadData];
        
        // 小菊花
        if (result != nil) {
            // 创建tableView
            [self createTableView];
            // 创建轮播图
            [self createCirculateView];
            
            [UIView animateWithDuration:3 animations:^{
                [self.HUD removeFromSuperview];
            }];
        }else{
            self.HUD.labelText = @"您的网路状况不是太好!";
        }
    }];
}
#pragma mark - 轮播图
- (void)createCirculateView
{
    // 取消额外的默认选区
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(ScreenWidth, ScreenWidth);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    
    self.circulateView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, -ScreenWidth * 0.6, ScreenWidth, ScreenWidth * 0.6) collectionViewLayout:layout];
    self.circulateView.backgroundColor = RGBA(253, 244, 233, 1);
    self.circulateView.delegate = self;
    self.circulateView.dataSource = self;
    // 分页滚动
    self.circulateView.pagingEnabled = YES;
    // 禁止边缘拖拽
    self.circulateView.bounces = NO;
    // 根据高度自适应宽度
    self.circulateView.contentMode = UIViewContentModeScaleAspectFill;
    [self.tableView addSubview:self.circulateView];
    [self.circulateView registerClass:[CirculateCollectionViewCell class] forCellWithReuseIdentifier:@"circulateCell"];
    // 轮播图页码
    UIPageControl *page = [[UIPageControl alloc] initWithFrame:CGRectMake(self.circulateView.frame.size.width / 2 - 10, -ScreenWidth * 0.08, 20, 20)];
    //    page.backgroundColor = [UIColor blackColor];
    page.currentPageIndicatorTintColor = [UIColor orangeColor];
    page.pageIndicatorTintColor = [UIColor whiteColor];
    page.numberOfPages = 5;
    page.currentPage = 0;
    [self.tableView addSubview:page];
    page.tag = 2000;
    // 定时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(circulateAction) userInfo:nil repeats:YES];
}
#pragma mark - collectionView的协议方法
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CirculateCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"circulateCell" forIndexPath:indexPath];
    cell.model = self.circulate_dataArr[indexPath.row];
    return cell;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.circulate_dataArr.count;
}
// 自动轮播
- (void)circulateAction
{
    [self.circulateView setContentOffset:CGPointMake(self.circulateView.contentOffset.x + ScreenWidth, 0) animated:YES];
    // 判断到达最后一页
    if (self.circulateView.contentOffset.x / ScreenWidth == 5) {
        self.circulateView.contentOffset = CGPointZero;
    }
}
//开始拖拽视图
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    contentOffsetY = scrollView.contentOffset.y;
}

// 完成拖拽(滚动停止时调用此方法，手指离开屏幕前)
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    oldContentOffsetY = scrollView.contentOffset.y;
    
}
#pragma mark - 页码跟随 + 下拉放大轮播图片
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.y == 0) {
        self.navigationController.navigationBarHidden = NO;
    }
    newContentOffsetY = scrollView.contentOffset.y;
    if (newContentOffsetY > oldContentOffsetY && oldContentOffsetY > contentOffsetY) { //向上滚动
        NSLog(@"up");
        
    } else if (newContentOffsetY < oldContentOffsetY && oldContentOffsetY < contentOffsetY) {
        //向下滚动
            NSLog(@"down");
        } else {
            NSLog(@"dragging");
        }
    
    if (scrollView.dragging) { //拖拽
        NSLog(@"scrollView.dragging");
        NSLog(@"contentOffsetY: %f", contentOffsetY);
        NSLog(@"newContentOffsetY: %f", scrollView.contentOffset.y);
        if ((scrollView.contentOffset.y - contentOffsetY) > 5.0f) {
            // 向上拖拽
            // 隐藏导航栏和选项栏
            [self.navigationController setNavigationBarHidden:YES animated:YES];
            //[self.navigationController setToolbarHidden:!hidden animated:YES];
            
            self.tabBarController.tabBar.hidden = YES;
            
        } else if ((contentOffsetY - scrollView.contentOffset.y) >
                  2.0f) { // 向下拖拽
            
            // 显示导航栏
            [self.navigationController setNavigationBarHidden: NO animated:YES];
            //[self setToolbarHidden:NO animated:YES];
            self.tabBarController.tabBar.hidden = NO;
            
        } else {
            
        }
    }
    UIPageControl *p = (UIPageControl *)[self.view viewWithTag:2000];
    // 拖拽之后,如果在最后一页, 返回第一页
    if (scrollView.contentOffset.x / ScreenWidth == 5) {
        scrollView.contentOffset = CGPointZero;
    }
    // 设置当前页码
    p.currentPage = scrollView.contentOffset.x / ScreenWidth;
    // 下拉放大
    CGPoint offset = scrollView.contentOffset;
    if (offset.y < 0) {
        CGRect rect = self.circulateView.frame;
        rect.origin.y = offset.y;
        rect.size.height =  -offset.y;
        self.circulateView.frame = rect;
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // 一次滚动的结束
    if (scrollView.contentOffset.x / ScreenWidth == 5) {
        scrollView.contentOffset = CGPointZero;
    }
    NSLog(@"已经结束减速");
    // 设置当前页码
    UIPageControl *pc =(UIPageControl *)[self.view viewWithTag:2000];
    pc.currentPage = scrollView.contentOffset.x / ScreenWidth;
}
#pragma mark - 创建tableView
- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.bounces = NO;
    self.tableView.separatorStyle = UITableViewCellAccessoryNone;
    self.tableView.contentInset = UIEdgeInsetsMake(ScreenWidth * 0.6, 0, 0, 0);
    self.tableView.backgroundColor = RGBA(253, 244, 233, 1);
    self.tableView.contentMode = UIViewContentModeScaleAspectFill;
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[ExploreTableViewCell class] forCellReuseIdentifier:@"travelCell"];
    [self.tableView registerClass:[ExploreStoryTableViewCell class] forCellReuseIdentifier:@"storyCell"];
}
#pragma mark - tableView协议方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        ExploreStoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"storyCell"];
        cell.backgroundColor = RGBA(253, 244, 233, 1);
        cell.story_dataArr = self.story_dataArr;
        // 传用户数据
        cell.imgName_dataArr = self.story_UserArr;
        // 设置代理人
        cell.delegate = self;
        return cell;
    }
    else {
        ExploreTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"travelCell"];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        cell.model = self.travel_dataArr[indexPath.row];
        // 传头像和名字数组
        cell.imgName_Model = self.travel_UserArr[indexPath.row];
        return cell;
    }
}
#pragma mark - 代理人执行代理方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.circulateView) {
        // 跳转轮播图
        CirculateViewController *circulate = [[CirculateViewController alloc] init];
        // 当push的时候隐藏tabbar
        circulate.hidesBottomBarWhenPushed = YES;
        circulate.model = self.circulate_dataArr[indexPath.row];
        [self.navigationController pushViewController:circulate animated:YES];
    }else{
        // 跳转每日故事
        DetailStoryViewController *detail = [[DetailStoryViewController alloc ] init];
        detail.hidesBottomBarWhenPushed = YES;
        detail.idModel = self.story_idArr[indexPath.row];
        [self.navigationController pushViewController:detail animated:YES];
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else{
        return self.travel_dataArr.count;
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
#pragma mark - tableView点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 取消点击效果
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 1) {
        DetailTravelViewController *travel = [[DetailTravelViewController alloc] init];
        travel.hidesBottomBarWhenPushed = YES;
        travel.idModel = self.travel_idArr[indexPath.row];
        [self.navigationController pushViewController:travel animated:YES];
    }
    
}
#pragma mark - 分区头部视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
#pragma mark - 第一个分区头
    self.sectionOne_View = [[UIView alloc] initWithFrame:CGRectMake(0, 10, ScreenWidth, 0)];
    
    // 左边小label
    UILabel *blueLabel = [[UILabel alloc] init];
    blueLabel.layer.cornerRadius = 3;
    blueLabel.clipsToBounds = YES;
    blueLabel.backgroundColor = RGBA(62, 172, 190, 1);
    [self.sectionOne_View addSubview:blueLabel];
    
    [blueLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        //        make.centerY.mas_equalTo(self.sectionOne_View.mas_centerY);
        make.bottom.mas_equalTo(self.sectionOne_View.mas_bottom).offset(-5);
        make.left.mas_equalTo(self.sectionOne_View.mas_left).offset(10);
        make.size.mas_equalTo(CGSizeMake(6, 20));
    }];
    
    UILabel *sectionOne_name = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 90)];
    sectionOne_name.textColor = [UIColor grayColor];
    sectionOne_name.text = @"每日精选故事";
    [self.sectionOne_View addSubview:sectionOne_name];
    
    [sectionOne_name mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(blueLabel.mas_centerY);
        make.left.mas_equalTo(self.sectionOne_View.mas_left).offset(25);
        make.size.mas_equalTo(CGSizeMake(ScreenWidth, 40));
    }];
    
    UIButton *allBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.sectionOne_View addSubview:allBtn];
    [allBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [allBtn setTitle:@"全部" forState:UIControlStateNormal];
    [allBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    //    allBtn.backgroundColor = [UIColor redColor];
    [allBtn addTarget:self action:@selector(pushAction) forControlEvents:UIControlEventTouchUpInside];
    
    [allBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(blueLabel.mas_centerY);
        make.right.mas_equalTo(self.sectionOne_View.mas_right).offset(-10);
        make.size.mas_equalTo(CGSizeMake(80, 30));
    }];
    // 全部箭头
    UIImageView *btnImg = [[UIImageView alloc] initWithFrame:CGRectMake(allBtn.frame.size.width + 60, 5, 20, 20)];
    btnImg.image = [UIImage imageNamed:@"iconfont-to-all"];
    [allBtn addSubview:btnImg]; 
#pragma mark - 第二个分区头
    self.sectionTwo_View = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 0)];
    
    // 左边小label
    UILabel *blueLabel2 = [[UILabel alloc] init];
    blueLabel2.layer.cornerRadius = 3;
    blueLabel2.clipsToBounds = YES;
    blueLabel2.backgroundColor = RGBA(62, 172, 190, 1);
    [self.sectionTwo_View addSubview:blueLabel2];
    [blueLabel2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.sectionTwo_View.mas_centerY);
        make.left.mas_equalTo(self.sectionTwo_View.mas_left).offset(10);
        make.size.mas_equalTo(CGSizeMake(6, 20));
    }];
    
    UILabel *sectionTwo_name = [[UILabel alloc] init];
    sectionTwo_name.textColor = [UIColor grayColor];
    sectionTwo_name.text = @"精彩游记和专题";
    [self.sectionTwo_View addSubview:sectionTwo_name];
    
    [sectionTwo_name mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.sectionTwo_View.mas_centerY);
        make.left.mas_equalTo(self.sectionTwo_View.mas_left).offset(25);
        make.size.mas_equalTo(CGSizeMake(ScreenWidth, 40));
    }];
    
    if (section == 0) {
        return self.sectionOne_View;
    }else{
        return self.sectionTwo_View;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 40;
    }else{
        return 20;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return ScreenWidth;
    }else{
        return ScreenWidth * 0.6;
    }
}

#pragma mark - 跳转到全部故事页面
- (void)pushAction
{
    AllStoryViewController *all = [[AllStoryViewController alloc] init];
    all.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:all animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
